<?php
/**
 * Created by PhpStorm.
 * User: G
 * Date: 2021/3/27
 * Time: 下午3:25
 */

namespace app\api\command;

use app\admin\model\profit\ProfitDetail;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\api\model\wanlshop\Order;
use app\api\model\wanlshop\Pay;
use app\api\model\wanlshop\Shop;
use think\Exception;
use app\admin\model\profit\Agentapply as AgentApplyModel;

/*
 * 分润 至 用户余额 定时任务
 */

class Profit extends Command
{

    /**
     * 名称描述配置
     * @author G
     * @date 2021-03-27 下午4:08
     */
    protected function configure()
    {
        $this->setName('profit')->setDescription('Profit Command');
    }

    /**
     * 分润处理
     * @param Input $input
     * @param Output $output
     * @return int|null|void
     * @author G
     * @date 2021-03-27 下午5:25
     */
    protected function execute(Input $input, Output $output)
    {
        try {
            // 广告分润
            $this->ads_apply();

            // 代理商分润
            $this->agent_apply();

            // 订单流水分润
            $this->order_share();

            // 分润至余额
            $this->profit_share();

        }catch (Exception $e) {
            echo '失败: ' . $e->getMessage();
        }
    }

    /**
     * 广告分润
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author G
     * @date 2021-03-31 下午8:41
     */
    private function ads_apply()
    {
        // 业务处理
        $un_share_data = \app\admin\model\profit\AdsApply::where(['is_share' => 0, 'status' => 1])->select();
        if (!$un_share_data) {
            echo '暂无数据';
            return;
        }

        foreach ($un_share_data as $k => $v) {
            // 分润处理 50%收益 给申请人

            $temp_data = [
                'uid' => $v['uid'],
                'referrer_uid' => $v['uid'],
                're_referrer_uid' => 0,
                'p_uid' => 0,
                'c_uid' => 0,
                'referrer_price' => bcmul($v['price'], 0.5, 2),
                're_referrer_price' => 0,
                'p_price' => 0,
                'c_price' => 0,
                't_price' => 0,
                'print' => 9,
                'creat_time' => time(),
                'update_time' => time()
            ];


            $insert_res = ProfitDetail::insert($temp_data);
            if (!$insert_res) {
                throw new Exception('保存分润信息失败');
            }


            // 更新分润状态：已分润
            $update_agent_res = \app\admin\model\profit\AdsApply::where(['id' => $v['id']])->update([
                'is_share' => 1,
                'updatetime' => time(),
            ]);

            if(!$update_agent_res) {
                throw new Exception('更新分润状态失败');
            }

            echo '广告分润成功: ' . $v['mobile'] . PHP_EOL;
        }
    }

    /**
     * 订单流水分润
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author G
     * @date 2021-03-31 下午8:49
     */
    private function order_share()
    {
        // 查询确认收货 未分润的订单
        $un_share_orders = Order::where(['state' => 4, 'is_share' => 0])->select();
        if (!$un_share_orders) {
            echo '暂无数据';exit;
        }


        foreach ($un_share_orders as $k => $v) {
            // 查询店铺信息
            $shop_info = Shop::where('id', $v['shop_id'])->find();
            if (!$shop_info) {
                echo '暂无店铺信息'; continue;
            }

            // 店铺商家id（用户id）
            $user_info = User::where('id', $shop_info['user_id'])->find();

            // 订单商品金额
            $order_price_info = Pay::where(['order_id' => $v['id']])->find();
            $order_price = $order_price_info['actual_payment'];

            $referrer_price = $c_price = bcmul($order_price, 0.001, 2);
            $p_price = bcmul($order_price,0.002, 2);

            $t_price = bcadd(bcadd($referrer_price, $p_price, 2), $c_price, 2);

            $temp_data = [
                'uid' => $user_info['id'],
                'referrer_uid' => $user_info['referrer_uid'],
                'p_uid' => $user_info['p_uid'],
                'c_uid' => $user_info['c_uid'],
                'referrer_price' => $referrer_price,
                'p_price' => $p_price,
                'c_price' => $c_price,
                't_price' => $t_price,
                'print' => 8,   //方案8
                'creat_time' => time(),
                'update_time' => time()
            ];

            // 插入分润表
            $insert_detail_res = ProfitDetail::insert($temp_data);
            if (!$insert_detail_res) {
                throw new Exception('保存分润信息失败');
            }

            // 修改订单分润状态
            $update_order_res = Order::where('id', $v['id'])->update([
                'is_share' => 1,
                'updatetime' => time(),
            ]);
            if (!$update_order_res) {
                throw new Exception('修改订单分润状态失败');
            }

            echo "订单流水分润成功 订单号：{$v['id']}" . PHP_EOL;
        }
    }


    /**
     * 代理商申请分润
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author G
     * @date 2021-03-31 下午8:46
     */
    private function agent_apply()
    {
        // 业务处理
        $un_share_data = AgentApplyModel::where(['is_share' => 0, 'status' => 1])->select();
        if (!$un_share_data) {
            echo '暂无数据';
            return;
        }

        foreach ($un_share_data as $k => $v) {
            // 更新 用户代理身份
            $update_group_res = User::where(['id' => $v['uid']])->update(['group_id' => $v['type'], 'updatetime' => time()]);
            if (!$update_group_res) {
                throw new Exception('更新用户代理身份信息失败');
            }

            // 查询申请人信息
            $apply_user_info = User::where('id', $v['uid'])->find();
            // 查询推荐人信息
            $invite_user_info = User::where('id', $v['p_uid'])->find();

            $temp_data = [
                'uid' => $apply_user_info['id'],
                'referrer_uid' => $v['p_uid'],
                're_referrer_uid' => $invite_user_info['referrer_uid'],
                'p_uid' => $apply_user_info['p_uid'],
                'c_uid' => $apply_user_info['c_uid'],
                'referrer_price' => 0,
                're_referrer_price' => 0,
                'p_price' => 0,
                'c_price' => 0,
                't_price' => 0,
                'print' => 0,
                'creat_time' => time(),
                'update_time' => time()
            ];

            if (!$invite_user_info || $invite_user_info['group_id'] == 1) {
                if ($v['type'] == 4 || (!$apply_user_info['p_uid'] && !$apply_user_info['c_uid'])) {
                    continue;
                } else {
                    if ($v['type'] == 3) {
                        // 方案 3
                        $temp_data['c_price'] = 10000;
                        $temp_data['print'] = 3;
                        $temp_data['t_price'] += 10000;
                    }
                }
            } else {
                if ($v['type'] == 3) {
                    // fixme 申请区代 需要查询是否有市代
                    $city_agent_user = User::where(['group_id' => 4, 'county_id' => $v['cc_id']])->find();
                    if ($city_agent_user) {
                        User::where(['id' => $v['uid']])->update(['c_uid' => $city_agent_user['id'], 'updatetime' => time()]);
                        // 重写市级代理
                        $temp_data['c_uid'] = $city_agent_user['id'];
                    }

                    if ($invite_user_info['group_id'] == 2) {
                        // 方案 4
                        $temp_data['referrer_price'] = 5000;
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;
                        $temp_data['c_price'] = 3000;
                        $temp_data['print'] = 4;
                        $temp_data['t_price'] += 8000;
                    } else {
                        // 方案 5
                        $temp_data['referrer_price'] = 10000;
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;;
                        $temp_data['c_price'] = 3000;
                        $temp_data['print'] = 5;
                        $temp_data['t_price'] += 13000;
                    }
                } else if ($v['type'] == 4) {
                    // fixme 申请市代
                    if ($invite_user_info['group_id'] == 4) {
                        // 方案 7
                        $temp_data['referrer_price'] = 100000;
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;;
                        $temp_data['print'] = 7;
                        $temp_data['t_price'] += 100000;
                    } else {
                        // 方案 6
                        $temp_data['referrer_price'] = 50000;
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;;
                        $temp_data['print'] = 6;
                        $temp_data['t_price'] += 50000;
                    }
                }
            }

            $insert_res = ProfitDetail::insert($temp_data);
            if (!$insert_res) {
                throw new Exception('保存分润信息失败');
            }


            // 更新 用户表邀请人信息
            if (!$apply_user_info['referrer_uid']) {
                $update_referrer = User::where(['id' => $apply_user_info['id']])->update([
                    'province_id' => $v['p_id'],
                    'province_name' => $v['p_name'],
                    'city_id' => $v['c_id'],
                    'city_name' => $v['c_name'],
                    'county_id' => $v['cc_id'],
                    'county_name' => $v['cc_name'],
                    'referrer_uid' => $invite_user_info['id'],
                    'updatetime' => time()
                ]);
                if (!$update_referrer) {
                    throw new Exception('更新邀请人信息失败');
                }
            }

            // 更新区域代理信息
            if ($v['type'] == 3) {
                User::where(['county_id' => $v['cc_id']])
                    ->where('group_id', '<', 3)
                    ->where('group_id', '>', 1)
                    ->update([
                        'p_uid' => $apply_user_info['id'],
                        'updatetime' => time(),
                    ]);
            } else if ($v['type'] == 4) {
                User::where(['city_id' => $v['c_id']])
                    ->where('group_id', '<', 4)
                    ->where('group_id', '>', 1)
                    ->update([
                        'c_uid' => $apply_user_info['id'],
                        'updatetime' => time(),
                    ]);
            }

            // 更新分润状态：已分润
            $update_agent_res = AgentApplyModel::where(['id' => $v['id']])->update([
                'is_share' => 1,
                'updatetime' => time(),
            ]);

            if(!$update_agent_res) {
                throw new Exception('更新分润状态失败');
            }

            echo '代理商分润成功: ' . $v['mobile'] . PHP_EOL;

        }
    }



    /**
     * 分润至余额
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author G
     * @date 2021-03-31 下午8:41
     */
    private function profit_share()
    {
        $profit_info = ProfitDetail::where(['status' => 0])->select();
        foreach ($profit_info as $k => $v) {

            // 获取分润配置明细
            $profit_config_info = $this->profit_config($v['print']);

            $v['referrer_uid'] && $v['referrer_price'] && User::money( $v['referrer_price'], $v['referrer_uid'], $profit_config_info);
            $v['re_referrer_uid'] && $v['re_referrer_price'] && User::money( $v['re_referrer_price'], $v['re_referrer_uid'], $profit_config_info);
            $v['p_uid'] && $v['p_price'] && User::money( $v['p_price'], $v['p_uid'], $profit_config_info);
            $v['c_uid'] && $v['c_price'] && User::money( $v['c_price'], $v['c_uid'], $profit_config_info);

            $update_res = ProfitDetail::where(['id' => $v['id']])->update([
                'status' => 1,
                'profit_time' => time(),
            ]);
            if(!$update_res) {
                throw new Exception('更新分润信息失败');
            }

            echo '分润至余额成功: ' . $v['mobile'] . PHP_EOL;
        }
    }

    /**
     * 获取 分润配置明细
     *
     * @param $id
     * @return string
     * @author G
     * @date 2021-08-13 上午10:40
     */
    private function profit_config($id)
    {

        $config_info = "";

        switch ($id) {
            case 1:
                $config_info = "推广365会员收益（分润方案：1）";
                break;
            case 2:
                $config_info = "推广365会员收益（分润方案：2）";
                break;
            case 3:
                $config_info = "推广区级代理收益（分润方案：3）";
                break;
            case 4:
                $config_info = "推广区级代理收益（分润方案：4）";
                break;
            case 5:
                $config_info = "推广区级代理收益（分润方案：5）";
                break;
            case 6:
                $config_info = "推广市级代理收益（分润方案：6）";
                break;
            case 7:
                $config_info = "推广市级代理收益（分润方案：7）";
                break;
            case 8:
                $config_info = "流水分润（分润方案：8）";
                break;
            case 9:
                $config_info = "广告分润（分润方案：9）";
                break;
            case 10:
                $config_info = "直推分润（分润方案：10）";
                break;
        }

        return $config_info;

    }

}